package com.easy.carl.algorithm.tree;

import com.easy.leetcode.tree.TreeNode;

import java.util.*;

//后序遍历
public class PostorderTraversal145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        //结果
        ArrayList<Integer> list = new ArrayList<>();
        //返回条件
        if (root == null) {
            return list;
        }
        //左右中
        list.addAll(postorderTraversal(root.left));
        list.addAll(postorderTraversal(root.right));
        list.add(root.val);
        return list;
    }

    //后序遍历 迭代
    public List<Integer> postorderTraversal1(TreeNode root) {
        //TODO
        //结果
        List<Integer> list = new ArrayList<>();
        //空直接返回
        if (root == null) {
            return list;
        }
        //队列存放
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.push(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            list.add(node.val);
            if (node.left != null) {
                queue.push(node.left);
            }
            if (node.right != null) {
                queue.push(node.right);
            }
        }
        Collections.reverse(list);
        return list;
    }

}
